<template>
  <div class="cart">
    <h2>购物车</h2>
    
    <div v-if="cartItems.length === 0">
      <p>购物车是空的</p>
    </div>
    
    <div v-else>
      <div v-for="item in cartItems" :key="item.id" class="cart-item">
        <span>{{ item.name }}</span>
        <span>- ¥{{ item.price }}</span>
        <span>- 数量: {{ item.quantity }}</span>
        <button @click="incrementQuantity(item.id)">+</button>
        <button @click="decrementQuantity(item.id)">-</button>
      </div>
      
      <div class="total">
        <h3>总价：¥{{ totalPrice }}</h3>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  computed: {
    // 获取购物车中的商品
    cartItems() {
      return this.$store.getters.cartItems
    },
    // 获取购物车总价
    totalPrice() {
      return this.$store.getters.totalPrice
    }
  },
  methods: {
    // 增加商品数量
    incrementQuantity(productId) {
      this.$store.dispatch('incrementQuantity', productId)
    },
    // 减少商品数量
    decrementQuantity(productId) {
      this.$store.dispatch('decrementQuantity', productId)
    }
  }
}
</script>

<style scoped>
.cart {
  margin-top: 20px;
  padding: 15px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.cart-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  align-items: center;
}

button {
  width: 25px;
  margin: 0 5px;
  padding: 0;
}

.total {
  margin-top: 20px;
  font-weight: bold;
  text-align: right;
}
</style>